﻿using DeZhen.Core.Consul.Platform;
using DeZhen.Core.Framework.Business.Ioc;
using DeZhen.Core.Framework.Conmon;
using DeZhen.Core.Framework.Entity;
using DeZhen.Core.Framework.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace DeZhen.Core.Consul.Client
{
    [Service]
    public class ConsulHttpClient : IConsulHttpClient
    {
        [Autowired]
        private IConsulPlatform _consulPlatform;
        [Autowired]
        private IHttpClient _httpClient;
        public ConsulHttpClient(IAutowiredPlatform autowiredService)
        {
            autowiredService.Autowired(this);
        }

        public string Get(string url, Dictionary<string, string> heads = null)
        {
            return _httpClient.Get(ResolveAddress(url), heads);
        }

        public async Task<string> GetAsync(string url, Dictionary<string, string> heads = null)
        {
            return await _httpClient.GetAsync(ResolveAddress(url), heads);
        }

        public string Post(string url, string json, Dictionary<string, string> heads = null)
        {
            return _httpClient.Post(ResolveAddress(url), json, heads);
        }

        public async Task<string> PostAsync(string url, string json, Dictionary<string, string> heads = null)
        {
            return await _httpClient.PostAsync(ResolveAddress(url), json, heads);
        }
        private String ResolveAddress(String url)
        {
            String serviceAddress = url.Split("//")[1];
            String serviceName = serviceAddress.Substring(0, serviceAddress.IndexOf("/"));
            String instanceAddress = _consulPlatform.GetServerAsync(serviceName).Result;
            return url.Replace(serviceName, instanceAddress);
             
        }
    }
}
